#include <stdio.h>
#include <stdlib.h>

enum {
	MEMOP_NONE = 0,
	MEMOP_READ = 1,
	MEMOP_WRITE = 2,
};

FILE* fdinero;
void output_dinero(unsigned int pc, unsigned int addr, int memop) {
	if ( !fdinero ) {
		fdinero = fopen("dinero.din", "w");
		if ( !fdinero ) return;
	}

	fprintf(fdinero, "2 %x\n", pc );
	if ( memop == MEMOP_READ ) {
		fprintf(fdinero, "0 %x\n", addr);
	} else if ( memop == MEMOP_WRITE ) {
		fprintf(fdinero, "1 %x\n", addr);
	}
}

int main (int argc, char** argv) {
	if ( argc < 2 ) {
		fprintf(stderr, "usage: ./inflator [decompressed file]\n");
		exit(1);
	}
	char* filename = argv[1];
	FILE* fraw = fopen(filename,"rb");
	if ( !fraw ) {
		fprintf(stderr, "Failed to open decompressed.bin!\n");
		exit(1);
	}
//	FILE* fdecomprstring = fopen("trace.log", "w");

	while ( !feof(fraw) ) {
	/*
 	371 MEM_READ 00004007f4d4 04 4007fe18
  372 REG 02 00 4007fe18
	373 STEP400438
	*/
		unsigned int buf[4] = {0};

		fread(buf, sizeof(unsigned int), 4, fraw);
		unsigned int flags = buf[0];
		unsigned int addr = buf[1];
		unsigned int value = buf[2];
		unsigned int pc = buf[3];

		unsigned char regChange = (flags>>16)&1;
		unsigned char memAcc = (flags>>17)&3;
		unsigned char size = (flags>>19)&31;
		unsigned char target = (flags>>24)&31;
/*
		if (memAcc == 1) { // memAccRead
			fprintf( fdecomprstring, "MEM_READ %012x %02d %x\n", addr, size, value );
		} else if (memAcc == 2) {                              
			fprintf( fdecomprstring, "MEM_WRITE %012x %02d %x\n", addr, size, value );
		}                                                       
		if (regChange) {                    
			fprintf( fdecomprstring, "REG %02d 00 %x\n", target, value );
		}                                             
		fprintf( fdecomprstring, "STEP%x\n#\n", pc );
*/
		output_dinero(flags, addr, memAcc);
	}

	return 0;
}
